/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package general.converters;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

/**
 *
 * @author isaias
 */
@FacesConverter(value = "monetaryConverter")
public class MonetaryConverter implements Converter, Serializable {

    public static NumberFormat numberFormat = new DecimalFormat("R$ #,##0.00");

    public Object getAsObject(FacesContext fc, UIComponent uic, String value) {

       
        if (value.startsWith("R$")) {
            value = value.substring(3);
        }

        value = value.replaceAll("\\.", "");
        value = value.replaceAll(",", ".");

        if (value.isEmpty()) {
            value = "0.0";
        }

        try {
            Double d = Double.parseDouble(value);
            return d;
        } catch (NumberFormatException nfe) {
            nfe.printStackTrace();
            return null;
        }

    }

    public String getAsString(FacesContext fc, UIComponent uic, Object value) {
        try {

            return numberFormat.format(value);
        } catch (Exception ex) {
            return "Erro";
        }
    }
}
